<template>
  <form class="v-form" :class="[
    labelPosition ? 'v-form--label-' + labelPosition : '',
    { 'v-form--inline': inline }
  ]">
    <slot></slot>
  </form>
</template>
<script>
  export default {
    name: 'VForm',
    componentName: 'VForm',
    props: {
      model: Object,
      rules: Object,
      labelPosition: String,
      labelWidth: String,
      labelSuffix: {
        type: String,
        default: '',
      },
      inline: Boolean,
      showMessage: {
        type: Boolean,
        default: true,
      },
    },
    watch: {
      rules() {
        this.validate();
      },
    },
    data() {
      return {
        fields: [],
      };
    },
    created() {
      this.$on('v.form.addField', (field) => {
        if (field) {
          this.fields.push(field);
        }
      });
      /* istanbul ignore next */
      this.$on('v.form.removeField', (field) => {
        if (field.prop) {
          this.fields.splice(this.fields.indexOf(field), 1);
        }
      });
    },
    methods: {
      resetFields() {
        if (!this.model) {
          /* eslint no-unused-expressions: 0 */
          process.env.NODE_ENV !== 'production' &&
          console.warn('[Vuego Warn][Form]model is required for resetFields to work.');
          return;
        }
        this.fields.forEach((field) => {
          field.resetField();
        });
      },
      validate(callback) {
        if (!this.model) {
          console.warn('[Vuego Warn][Form]model is required for validate to work!');
          return;
        }
        let valid = true;
        let count = 0;
        // 如果需要验证的fields为空，调用验证时立刻返回callback
        if (this.fields.length === 0 && callback) {
          callback(true);
        }
        this.fields.forEach((field) => {
          field.validate('', (errors) => {
            if (errors) {
              valid = false;
            }
            count += 1;
            if (typeof callback === 'function' && count === this.fields.length) {
              callback(valid);
            }
          });
        });
      },
      validateField(prop, cb) {
        const fieldVal = this.fields.filter(field => field.prop === prop)[0];
        if (!fieldVal) { throw new Error('must call validateField with valid prop string!'); }

        fieldVal.validate('', cb);
      },
    },
  };
</script>
